<template>
  <div class="enhanced-signature-pad">
    <div class="toolbar">
      <div class="color-picker">
        <span>颜色:</span>
        <button
          v-for="color in colors"
          :key="color"
          :class="['color-btn', { active: currentColor === color }]"
          :style="{ backgroundColor: color }"
          @click="changeColor(color)"
        ></button>
      </div>
      
      <div class="brush-size">
        <span>粗细:</span>
        <input
          type="range"
          min="1"
          max="10"
          v-model="currentLineWidth"
          @change="changeLineWidth"
        >
        <span>{{ currentLineWidth }}px</span>
      </div>
      
      <div class="actions">
        <button @click="undo" :disabled="!canUndo" class="btn btn-secondary">撤销</button>
        <button @click="clearCanvas" class="btn btn-secondary">清空</button>
        <button @click="saveSignature" :disabled="!hasSignature" class="btn btn-primary">
          保存签名
        </button>
      </div>
    </div>
    
    <div class="canvas-container" :style="containerStyle">
      <canvas
        ref="canvas"
        :width="width"
        :height="height"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrawing"
        class="signature-canvas"
      ></canvas>
      <div v-if="!hasSignature" class="placeholder">
        请在此处签名
      </div>
    </div>
    
    <div v-if="imageUrl" class="preview-section">
      <h4>签名预览</h4>
      <img :src="imageUrl" alt="签名预览" class="preview-img" />
      <div class="preview-actions">
        <button @click="downloadSignature" class="btn btn-outline">下载</button>
        <button @click="copyToClipboard" class="btn btn-outline">复制</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'EnhancedSignaturePad',
  props: {
    width: {
      type: Number,
      default: 800
    },
    height: {
      type: Number,
      default: 400
    },
    lineColor: {
      type: String,
      default: '#000000'
    },
    lineWidth: {
      type: Number,
      default: 3
    },
    backgroundColor: {
      type: String,
      default: '#ffffff'
    }
  },
  data() {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      imageUrl: '',
      hasSignature: false,
      currentColor: this.lineColor,
      currentLineWidth: this.lineWidth,
      colors: ['#000000', '#ff0000', '#0000ff', '#008000', '#ffa500'],
      history: [],
      maxHistory: 10
    }
  },
  computed: {
    containerStyle() {
      return {
        width: `${this.width}px`,
        height: `${this.height}px`
      }
    },
    canUndo() {
      return this.history.length > 0
    }
  },
  mounted() {
    this.setupCanvas()
    this.saveToHistory()
  },
  methods: {
    setupCanvas() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      
      ctx.fillStyle = this.backgroundColor
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      
      this.updateCanvasStyle()
    },
    
    updateCanvasStyle() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      
      ctx.strokeStyle = this.currentColor
      ctx.lineWidth = this.currentLineWidth
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
    },
    
    startDrawing(e) {
      this.isDrawing = true
      const point = this.getCoordinates(e)
      this.lastX = point.x
      this.lastY = point.y
    },
    
    draw(e) {
      if (!this.isDrawing) return
      
      e.preventDefault()
      
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      const point = this.getCoordinates(e)
      
      ctx.beginPath()
      ctx.moveTo(this.lastX, this.lastY)
      ctx.lineTo(point.x, point.y)
      ctx.stroke()
      
      this.lastX = point.x
      this.lastY = point.y
      this.hasSignature = true
    },
    
    stopDrawing() {
      if (this.isDrawing) {
        this.isDrawing = false
        this.saveToHistory()
      }
    },
    
    handleTouchStart(e) {
      e.preventDefault()
      this.startDrawing(e)
    },
    
    handleTouchMove(e) {
      e.preventDefault()
      this.draw(e)
    },
    
    getCoordinates(e) {
      const canvas = this.$refs.canvas
      const rect = canvas.getBoundingClientRect()
      
      let clientX, clientY
      
      if (e.type.includes('touch')) {
        clientX = e.touches[0].clientX
        clientY = e.touches[0].clientY
      } else {
        clientX = e.clientX
        clientY = e.clientY
      }
      
      return {
        x: clientX - rect.left,
        y: clientY - rect.top
      }
    },
    
    clearCanvas() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = this.backgroundColor
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      
      this.updateCanvasStyle()
      this.imageUrl = ''
      this.hasSignature = false
      this.history = []
      this.$emit('cleared')
    },
    
    saveSignature() {
      const canvas = this.$refs.canvas
      const imageUrl = canvas.toDataURL('image/png')
      
      this.imageUrl = imageUrl
      this.$emit('save', imageUrl)
      
      // 同时发送 Blob 格式
      canvas.toBlob(blob => {
        this.$emit('save-blob', blob)
      }, 'image/png', 0.8)
    },
    
    changeColor(color) {
      this.currentColor = color
      this.updateCanvasStyle()
    },
    
    changeLineWidth() {
      this.updateCanvasStyle()
    },
    
    saveToHistory() {
      const canvas = this.$refs.canvas
      const imageData = canvas.toDataURL()
      
      this.history.push(imageData)
      
      // 限制历史记录数量
      if (this.history.length > this.maxHistory) {
        this.history.shift()
      }
    },
    
    undo() {
      if (this.history.length > 1) {
        this.history.pop() // 移除当前状态
        const previousState = this.history[this.history.length - 1]
        
        const img = new Image()
        img.onload = () => {
          const canvas = this.$refs.canvas
          const ctx = canvas.getContext('2d')
          ctx.clearRect(0, 0, canvas.width, canvas.height)
          ctx.drawImage(img, 0, 0)
        }
        img.src = previousState
        
        this.hasSignature = this.history.length > 1
      } else if (this.history.length === 1) {
        this.clearCanvas()
      }
    },
    
    downloadSignature() {
      if (!this.imageUrl) return
      
      const link = document.createElement('a')
      link.download = `signature-${new Date().getTime()}.png`
      link.href = this.imageUrl
      link.click()
    },
    
    async copyToClipboard() {
      if (!this.imageUrl) return
      
      try {
        const response = await fetch(this.imageUrl)
        const blob = await response.blob()
        await navigator.clipboard.write([
          new ClipboardItem({
            'image/png': blob
          })
        ])
        this.$message.success('签名已复制到剪贴板')
      } catch (err) {
        console.error('复制失败:', err)
        this.$message.error('复制失败')
      }
    },
    
    // 公共方法：获取签名数据
    getSignatureData() {
      return {
        base64: this.$refs.canvas.toDataURL('image/png'),
        blob: () => new Promise(resolve => {
          this.$refs.canvas.toBlob(resolve, 'image/png')
        })
      }
    },
    
    // 公共方法：设置签名（从外部加载）
    setSignatureFromBase64(base64String) {
      const img = new Image()
      img.onload = () => {
        const canvas = this.$refs.canvas
        const ctx = canvas.getContext('2d')
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(img, 0, 0)
        this.hasSignature = true
        this.imageUrl = base64String
        this.saveToHistory()
      }
      img.src = base64String
    }
  }
}
</script>

<style scoped>
.enhanced-signature-pad {
  font-family: Arial, sans-serif;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.color-picker, .brush-size, .actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-btn {
  width: 24px;
  height: 24px;
  border: 2px solid transparent;
  border-radius: 50%;
  cursor: pointer;
}

.color-btn.active {
  border-color: #333;
}

.brush-size input {
  width: 80px;
}

.btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.btn-secondary {
  background: white;
  color: #333;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
}

.canvas-container {
  position: relative;
  border: 2px dashed #ddd;
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.signature-canvas {
  display: block;
  cursor: crosshair;
  background: transparent;
}

.placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 18px;
  pointer-events: none;
}

.preview-section {
  margin-top: 20px;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
}

.preview-img {
  max-width: 300px;
  border: 1px solid #eee;
  margin: 8px 0;
}

.preview-actions {
  display: flex;
  gap: 8px;
}
</style>